import { useHttp } from ".";
import { cleanObject } from "../utils";
import { useQuery, useMutation, useQueryClient, QueryKey } from "react-query";
import {
  useOptimisticAddConfig,
  useOptimisticDeleteConfig,
  useOptimisticUpdateConfig,
} from "../utils/use-optimistic-options";
import { Project } from "../types/project";

// export const useQueryProject = (param?: Partial<Project>) => {
//   const client = useHttp();
//   const { run, ...result } = useAsync<Project[]>();
//   //这里将请求函数抽离，因为run只能拿到promise执行完的，所以无法再次触发请求
//   const fetchProject = useCallback(
//     () =>
//       client("/projects", {
//         data: cleanObject(param || {}),
//       }),
//     [param, client]
//   );
//   useEffect(() => {
//     run(fetchProject(), {
//       retry: fetchProject,
//     });
//   }, [param, run, fetchProject]);
//   return result;
// };

// export const useEditProject = () => {
//   const client = useHttp();
//   const { run, ...result } = useAsync<Project[]>();
//   const mutate = (param: Partial<Project>) => {
//     return run(
//       client(`/projects/${param.id}`, {
//         data: param,
//         method: "PATCH",
//       })
//     );
//   };
//   return {
//     mutate,
//     result,
//   };
// };

//使用react-query替换useAsync
export const useQueryProject = (param?: Partial<Project>) => {
  const client = useHttp();
  const data = cleanObject(param || {});
  return useQuery<Project[]>(["projects", data], () =>
    client("/projects", {
      data,
      method: "POST",
    })
  );
};

export const useEditProject = (queryKey: QueryKey) => {
  const client = useHttp();
  return useMutation(
    (param: Partial<Project>) =>
      client(`/projects/edit`, {
        data: param,
        method: "POST",
      }),
    // client(`/projects/${param.id}`, {
    //   data: param,
    //   method: "PATCH",
    // }),
    useOptimisticUpdateConfig(queryKey)
  );
};
export const useAddProject = (queryKey: QueryKey) => {
  const client = useHttp();
  return useMutation(
    (param: Partial<Project>) =>
      client(`/projects/create`, {
        data: param,
        method: "POST",
      }),
    useOptimisticAddConfig(queryKey)
  );
};
export const useDeleteProject = (queryKey: QueryKey) => {
  const client = useHttp();
  return useMutation(
    (param: Partial<Project>) =>
      client(`/projects/del`, {
        data: {
          id: param.id,
        },
        method: "POST",
      }),
    useOptimisticDeleteConfig(queryKey)
  );
};
/**
 * @description: 根据id查询项目详情，当id变化的时候触发请求，只有当id存在的时候请求才会触发
 * @param {number} id - 项目的id
 * @return {*}
 */
export const useQueryProjectDetail = (id?: number) => {
  const client = useHttp();
  return useQuery<Project>(
    ["projects", { id }],
    () => client(`/projects/${id}`),
    {
      enabled: Boolean(id), //只有当id存在时候才执行请求
    }
  );
};
